import threading

from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.schedulers import base
from apscheduler.schedulers.background import BackgroundScheduler


class MyBackgroundScheduler(BackgroundScheduler):
    executors = {
        'default': ThreadPoolExecutor(10),  # 线程 需要比max_instances大
        'processpool': ProcessPoolExecutor(5)  # 进程
    }
    job_defaults = {
        'coalesce': False,
        'max_instances': 10  # 最大线程数
    }

    def __init__(self):
        BackgroundScheduler.__init__(self,executors=self.executors, job_defaults=self.job_defaults)

    def start(self, *args, **kwargs):
        if self.state == base.STATE_STOPPED:
            BackgroundScheduler.start(self, *args, **kwargs)

    def shutdown(self, *args, **kwargs):
        if self.state == base.STATE_RUNNING:
            BackgroundScheduler.shutdown(self,*args, **kwargs)

    def pause(self):
        if self.state == base.STATE_RUNNING:
            BackgroundScheduler.pause(self)

    def resume(self):
        if self.state == base.STATE_PAUSED:
            BackgroundScheduler.resume(self)
